﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Equipment.Dto;
using LimaLims.Core;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core.Entity.Equipment;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LimaLims.Application.Service.Equipment
{

    /// <summary>
    /// 设备厂家服务
    /// </summary>
    [ApiDescriptionSettings(Name = "EquipmentFactory", Order = 152)]
    [Route("api")]
    public class EquipmentFactoryService : IEquipmentFactoryService, IDynamicApiController, ITransient
    {
        private readonly IRepository<EquipmentFactory> _equipmentFactoryRep;  // 设备厂家表仓储

        public EquipmentFactoryService(IRepository<EquipmentFactory> equipmentFactory)
        {
            _equipmentFactoryRep = equipmentFactory;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("equipmentFactory/add")]
        public async Task Add(AddEquipmentFactoryInput input)
        {
            var isExist = await _equipmentFactoryRep.DetachedEntities.AnyAsync(u => u.Name == input.Name);
            if (isExist)
                throw Oops.Oh("已存在相同名称的厂家");

            var equipmentFactory = input.Adapt<EquipmentFactory>();

            await equipmentFactory.InsertAsync();
        }

        [HttpPost("equipmentFactory/delete")]
        public async Task Delete(long id)
        {
            var equipmentFactory = await _equipmentFactoryRep.Include(s=>s.EquipmentInfos).FirstOrDefaultAsync(u => u.Id == id);
            if (equipmentFactory == null)
                throw Oops.Oh("不存在此数据");

            if (equipmentFactory.EquipmentInfos.Count > 0)
            {
                throw Oops.Oh("此设备厂家已关联仪器设备信息，请勿直接删除！");
            }
            await equipmentFactory.DeleteAsync();
        }

        [HttpGet("equipmentFactory/detail")]
        public async Task<EquipmentFactory> Detail(long id)
        {
            var equipmentFactory = await _equipmentFactoryRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (equipmentFactory == null)
                throw Oops.Oh("不存在此数据！");
            return equipmentFactory;
        }

        [HttpPost("equipmentFactory/edit")]
        public async Task Edit(EditEquipmentFactoryInput input)
        {
            var equipmentFactory = await _equipmentFactoryRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (equipmentFactory == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _equipmentFactoryRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同名称的设备厂家");

            var equipmentFactoryModel = input.Adapt<EquipmentFactory>();

            await equipmentFactoryModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("equipmentFactory/selectList")]
        public async Task<List<SelectDto>> SelectList()
        {
            var list = await _equipmentFactoryRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectDto
            {
                Value = x.Id,
                Label = x.Name
            }).ToList();
        }

        [HttpGet("equipmentFactory/page")]
        public async Task<PageResult<EquipmentFactoryOutput>> QueryPage([FromQuery] EquipmentFactoryPageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var phone = !string.IsNullOrEmpty(input.Phone?.Trim());
            var equipmentFactorys = await _equipmentFactoryRep.DetachedEntities
                                         .Where((name, u => EF.Functions.Like(u.Name, $"%{input.SearchValue.Trim()}%")))
                                         .Where((phone, u => EF.Functions.Like(u.Phone, $"%{input.Phone.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new EquipmentFactoryOutput
                                         {
                                             Id = u.Id,
                                             Name = u.Name,
                                             ContactName = u.ContactName,
                                             Phone = u.Phone,
                                             Address = u.Address,
                                             Remark = u.Remark,
                                             ValidStatus = u.ValidStatus,
                                             Sort = u.Sort,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return equipmentFactorys;
        }
    }
}
